package com.farm.wsch.index.impl;

import java.io.IOException;
import java.nio.file.Paths;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexableField;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.wltea.analyzer.lucene.IKAnalyzer;

import com.farm.wsch.index.WschIndexServerInter;
import com.farm.wsch.index.pojo.IndexConfig;
import com.farm.wsch.index.pojo.IndexDocument;

public class WschIndexServerImpl implements WschIndexServerInter {
	private IndexConfig config;
	private IndexWriter indexWriter;

	public WschIndexServerImpl(IndexConfig config) throws IOException {
		this.config = config;
		Directory directory = FSDirectory.open(Paths.get(config.getIndexDir().getPath()));
		// Directory directory = new RAMDirectory();//保存索引到内存中 （内存索引库）
		// 官方推荐分词器，对中文不友好
		Analyzer analyzer = new IKAnalyzer();
		IndexWriterConfig iwconfig = new IndexWriterConfig(analyzer);
		indexWriter = new IndexWriter(directory, iwconfig);
	}

	@Override
	public void closeAndSubmit() throws IOException {
		indexWriter.close();
	}

	@Override
	public void addDocument(IndexDocument idoc) throws IOException {
		indexWriter.addDocument(idoc.getDocument());
	}

	@Override
	public void updateDocument(IndexDocument idoc) throws IOException {
		indexWriter.updateDocument(new Term(DefaultField.APPID.getKey(), idoc.getId()), idoc.getDocument());
	}

	@Override
	public void delDocument(String docid) throws IOException {
		indexWriter.deleteDocuments(new Term(DefaultField.APPID.getKey(), docid));
	}

	@Override
	public void mergeIndex() throws IOException {
		indexWriter.forceMerge(1);
	}

	@Override
	public void delAllIndex() throws IOException {
		indexWriter.deleteAll();
	}

	@Override
	public void delAppDocuments(String appkeyid) throws IOException {
		indexWriter.deleteDocuments(new Term(DefaultField.APPKEYID.getKey(), appkeyid));
	}
}
